package com.t360.cubesolver;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Read the pieces from an input file or generic reader. The input must only 
 * contain the characters 'o' ("full" part in a piece) or ' ' ("hole").
 * Sample input:
 * 
 *   o  o o o  o  
 *  ooo ooooo oooo
 * ooooo ooo oooo 
 *  ooo ooooo oooo
 *   o  o o o  o  
 *  o o  o o  o o 
 * oooo ooooo oooo
 *  oooo ooo oooo 
 * oooo ooooo oooo
 * oo o o o  oo oo
 * 
 * @author fmanganiello
 */
public class PuzzleReader {
	/**
	 * Read the list of pieces from a generic reader
	 * @param reader
	 * @return
	 * @throws IOException
	 */
	public static Puzzle fromReader(BufferedReader reader) throws IOException {
		int linesRead = 0;
		int piecesParsed = 0;
		
		// Each line contains 3 aligned lines associated to 3 different pieces.
		// Each line of a piece contain 5 sequences of [o ] characters.
		Pattern linePattern = Pattern.compile("^([o ]{5})([o ]{5})([o ]{5})\\s*$");
		Puzzle pieces = new Puzzle(6);
		StringBuffer piecesBuffer[] = new StringBuffer[6];
		for (int i=0; i < piecesBuffer.length; ++i) {
			piecesBuffer[i] = new StringBuffer("");
		}
		
		while (reader.ready()) {
			int indexBase = ((int) linesRead/5)*3;
			String curLine = reader.readLine();
			Matcher m = linePattern.matcher(curLine);
			
			if (m.matches()) {
				piecesBuffer[indexBase].append(m.group(1) + "\n");
				piecesBuffer[indexBase+1].append(m.group(2) + "\n");
				piecesBuffer[indexBase+2].append(m.group(3) + "\n");
			}
			
			linesRead++;
			
			if (linesRead % 5 == 0) {
				for (int i=indexBase; i < indexBase+3; ++i) {
					pieces.set(i, new PuzzlePiece(piecesBuffer[i].toString(), 0, 0, piecesParsed++));
				}
			}
		}
		
		reader.close();
		return pieces;
	}
	
	/**
	 * Read the list of pieces from an input file
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public static Puzzle fromFile(File file) throws IOException {
		return fromReader(new BufferedReader(new InputStreamReader(new FileInputStream(file))));
	}
}
